<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-alert
            title="添加商品信息"
            type="info"
            center
            show-icon
            :closable="false"
          >
          </el-alert>
        </el-col>
      </el-row>
      <!-- 步骤条 -->
      <el-steps
        :space="200"
        :active="stepIndex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 左侧tab栏 表单 一次性提交数据-->
      <el-form
        :model="GoodsForm"
        ref="addGoodsFormRef"
        :rules="addGoodsFormRules"
        label-position="top"
        label-width="100px"
      >
        <el-tabs
          :before-leave="tabBeforeLeave"
          tab-position="left"
          v-model="stepIndex"
          @tab-click="handleTabClick"
        >
          <!-- tab1 基本信息栏 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="GoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input
                v-model="GoodsForm.goods_price"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input
                v-model="GoodsForm.goods_weight"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input
                v-model="GoodsForm.goods_number"
                type="number"
              ></el-input>
            </el-form-item>
            <!--  商品所属分类-->
            <el-form-item prop="goods_cat" label="商品分类">
              <!-- 级联选择器 -->
              <el-cascader
                clearable
                collapse-tags
                v-model="GoodsForm.goods_cat"
                :options="cateList"
                :props="{
                  checkStrictly: true,
                  expandTrigger: 'hover',
                  value: 'cat_id',
                  label: 'cat_name',
                  children: 'children',
                }"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- tab2 商品参数栏 -->
          <el-tab-pane label="商品参数" name="1">
            <!-- 循环生成商品参数名称 -->
            <el-form-item v-for="(item, index) in manyData" :key="index">
              {{ item.attr_name }}
              <!-- 循环小的复选框 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :label="item2"
                  v-for="(item2, index2) in item.attr_vals"
                  :key="index2"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- tab3 商品属性栏 -->
          <el-tab-pane label="商品属性" name="2">
            <!-- 循环生成参数名称 -->
            <el-form-item v-for="(item, index) in onlyData" :key="index">
              {{ item.attr_name }}
              <!-- 循环生成input框 -->
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- tab4 商品图片栏 -->
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="header"
              :on-success="uploadSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <!-- tab5 商品内容栏 富文本编辑器 -->
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="GoodsForm.goods_introduce" />
            <!-- 新增商品按钮 -->
            <el-button type="primary" class="btnOk" @click="doAdd"
              >确认新增</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览弹出框 -->
    <el-dialog title="图片预览" :visible.sync="isShowPrve" width="50%">
      <img class="imgPrev" :src="previewPath" alt="图片预览" />
    </el-dialog>
  </div>
</template>
<script>
// 局部导入 深拷贝对象
import _ from 'lodash'

export default {
  created () {
    this.getCateList()
  },
  data () {
    return {
      stepIndex: '0',
      // 添加商品 数据参数对象
      GoodsForm: {
        goods_name: '',
        goods_price: '',
        goods_weight: '',
        goods_number: '',
        goods_cat: '',
        pics: [], // 图片模拟路径
        goods_introduce: '',
        attrs: []
      },
      // 添加商品 表单校验规则
      addGoodsFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
      // 级联选择器 绑定的分类数据列表数组
      cateList: [],
      // 动态数据
      manyData: [],
      // 静态属性数据
      onlyData: [],
      //   上传图片url
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      //   上传图片的 请求头token
      header: {
        Authorization: window.sessionStorage.getItem('token')
      },
      //
      previewPath: '',
      //
      isShowPrve: false
    }
  },
  computed: {
    cateId () {
      if (this.GoodsForm.goods_cat.length < 3) {
        return null
      }
      //   返回 分类下拉框 中选中的第三级菜单
      return this.GoodsForm.goods_cat[2]
    }
  },
  methods: {
    //  获取分类列表数据
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 保存列表数组
      this.cateList = res.data
    },
    // 监听分类下拉框 改变事件(tab栏切换)
    handleChange () {
      // 如果选中的类别数组元素少于三个 就清空选中项
      if (this.GoodsForm.goods_cat.length < 3) {
        this.GoodsForm.goods_cat.length = 0
      }
    },
    // 切换tab 栏事件
    tabBeforeLeave (activeName, oldActiveName) {
      if (oldActiveName === 0 && this.GoodsForm.goods_cat.length !== 3) {
        this.$message.warning('请选择商品分类哦~')
        return false // 阻止切换
      }
    },
    // tab 切换
    handleTabClick () {
      switch (this.stepIndex) {
        case '1': {
          this.step1() // 商品参数
          break
        }
        case '2': {
          this.step2() // 商品属性
          break
        }
      }
    },
    // 点击第一个tab栏 商品参数
    async step1 () {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: 'many' }
        }
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      res.data.forEach((ele) => {
        ele.attr_vals = ele.attr_vals.split(',')
      })
      this.manyData = res.data
    },
    // 点击第二个tab栏 商品属性
    async step2 () {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: 'only' }
        }
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.onlyData = res.data
    },
    // 图片预览事件
    handlePreview (file) {
      const fPath = file.response.data.url
      this.previewPath = fPath
      // 打开对话框
      this.isShowPrve = true
    },
    // 图片移除 组件事件
    handleRemove (removeFile) {
      const fPath = removeFile.response.data.tmp_path
      // 找对应的下标
      const fIndex = this.GoodsForm.pics.findIndex((ele) => {
        return ele.pics === fPath
      })
      // 根据下标 从数组中删除该图
      this.GoodsForm.pics.splice(fIndex, 1)
      this.$message.success('删除成功')
    },
    // 图片组件上传成功事件
    uploadSuccess (response) {
      this.GoodsForm.pics.push({
        pic: response.data.tmp_path
      })
    },
    // 新增商品事件
    doAdd () {
      this.$refs.addGoodsFormRef.validate(async (result) => {
        if (!result) {
          // 切换tab 到基本信息栏
          this.stepIndex = '0'
          return this.$message.error('数据未填写完整哦~')
        }
        // 处理接口中 attrs 参数 (将动态参数和静态属性通过遍历加到一个数组中)
        // 动态参数对象
        this.manyData.forEach((item) => {
          const temp = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.GoodsForm.attrs.push(temp)
        })
        // 静态属性对象
        this.onlyData.forEach((item) => {
          const temp = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.GoodsForm.attrs.push(temp)
        })
        // 通过后 发起请求 但接口goods_cat需要一个字符串 所以 复制一个参数对象
        const formData = _.cloneDeep(this.GoodsForm)
        formData.goods_cat = formData.goods_cat.join(',')
        // 发起请求
        const { data: res } = await this.$http.post('goods', formData)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.$router.push('/goods')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 5;
}
.imgPrev {
  width: 100%;
}
.btnOk {
  margin-top: 15px;
}
</style>
